// 评论服务 - 连接后端API
import axios from 'axios'

const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:9090/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证token
apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API Error:', error)
    if (error.response?.status === 401) {
      // 未授权，清除token并跳转到登录页
      localStorage.removeItem('auth_token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export const CommentService = {
  // 创建评论
  async create(ticketId, payload) {
    try {
      const response = await apiClient.post(`/comments/ticket/${ticketId}`, {
        content: payload.content,
        commentType: payload.commentType || 'PUBLIC',
        isInternal: payload.isInternal || false,
        parentId: payload.parentId || null
      })
      return response.data
    } catch (error) {
      console.error('创建评论失败:', error)
      throw new Error(error.response?.data?.message || '创建评论失败')
    }
  },

  // 更新评论
  async update(commentId, payload) {
    try {
      const response = await apiClient.put(`/comments/${commentId}`, {
        content: payload.content,
        editReason: payload.editReason || ''
      })
      return response.data
    } catch (error) {
      console.error('更新评论失败:', error)
      throw new Error(error.response?.data?.message || '更新评论失败')
    }
  },

  // 删除评论
  async delete(commentId) {
    try {
      await apiClient.delete(`/comments/${commentId}`)
      return true
    } catch (error) {
      console.error('删除评论失败:', error)
      throw new Error(error.response?.data?.message || '删除评论失败')
    }
  },

  // 获取工单评论
  async getTicketComments(ticketId) {
    try {
      const response = await apiClient.get(`/comments/ticket/${ticketId}`)
      return response.data || []
    } catch (error) {
      console.error('获取工单评论失败:', error)
      throw new Error(error.response?.data?.message || '获取工单评论失败')
    }
  },

  // 分页获取工单评论
  async getTicketCommentsPage(ticketId, params = {}) {
    try {
      const response = await apiClient.get(`/comments/ticket/${ticketId}/page`, { params })
      return response.data || []
    } catch (error) {
      console.error('获取工单评论失败:', error)
      throw new Error(error.response?.data?.message || '获取工单评论失败')
    }
  },

  // 获取工单公开评论
  async getPublicTicketComments(ticketId) {
    try {
      const response = await apiClient.get(`/comments/ticket/${ticketId}/public`)
      return response.data || []
    } catch (error) {
      console.error('获取公开评论失败:', error)
      throw new Error(error.response?.data?.message || '获取公开评论失败')
    }
  },

  // 获取工单内部评论
  async getInternalTicketComments(ticketId) {
    try {
      const response = await apiClient.get(`/comments/ticket/${ticketId}/internal`)
      return response.data || []
    } catch (error) {
      console.error('获取内部评论失败:', error)
      throw new Error(error.response?.data?.message || '获取内部评论失败')
    }
  },

  // 获取工单顶级评论
  async getTopLevelComments(ticketId) {
    try {
      const response = await apiClient.get(`/comments/ticket/${ticketId}/top-level`)
      return response.data || []
    } catch (error) {
      console.error('获取顶级评论失败:', error)
      throw new Error(error.response?.data?.message || '获取顶级评论失败')
    }
  },

  // 获取评论回复
  async getCommentReplies(commentId) {
    try {
      const response = await apiClient.get(`/comments/${commentId}/replies`)
      return response.data || []
    } catch (error) {
      console.error('获取评论回复失败:', error)
      throw new Error(error.response?.data?.message || '获取评论回复失败')
    }
  },

  // 获取用户评论
  async getUserComments(userId, params = {}) {
    try {
      const response = await apiClient.get(`/comments/user/${userId}`, { params })
      return response.data || []
    } catch (error) {
      console.error('获取用户评论失败:', error)
      throw new Error(error.response?.data?.message || '获取用户评论失败')
    }
  },

  // 获取工单评论数量
  async getTicketCommentCount(ticketId) {
    try {
      const response = await apiClient.get(`/comments/ticket/${ticketId}/count`)
      return response.data
    } catch (error) {
      console.error('获取评论数量失败:', error)
      throw new Error(error.response?.data?.message || '获取评论数量失败')
    }
  },

  // 点赞评论
  async likeComment(commentId) {
    try {
      const response = await apiClient.post(`/comments/${commentId}/like`)
      return response.data
    } catch (error) {
      console.error('点赞评论失败:', error)
      throw new Error(error.response?.data?.message || '点赞评论失败')
    }
  },

  // 点踩评论
  async dislikeComment(commentId) {
    try {
      const response = await apiClient.post(`/comments/${commentId}/dislike`)
      return response.data
    } catch (error) {
      console.error('点踩评论失败:', error)
      throw new Error(error.response?.data?.message || '点踩评论失败')
    }
  },

  // 获取评论详情
  async getCommentById(commentId) {
    try {
      const response = await apiClient.get(`/comments/${commentId}`)
      return response.data
    } catch (error) {
      console.error('获取评论详情失败:', error)
      throw new Error(error.response?.data?.message || '获取评论详情失败')
    }
  }
}
